import Vue from "vue";
export default {
	namespaced: true,
	state: {
		activeTag: "Home",
		tags: {
			Home: "首页",
		},
	},
	mutations: {
		/**
		 * 添加 tag
		 * @param {*} key: tag 的 key
		 * @param {*} value: tag 的 value
		 */
		addTag(state, { key, value }) {
			if (!(key in state.tags)) {
				Vue.set(state.tags, key, value);
			}
			state.activeTag = key;
		},
		/**
		 * tag 的批量关闭
		 * @param {*} type: 批量关闭的规则
		 */
		closeTagBatch(state, type) {
			let keys = Object.keys(state.tags).slice(1);
			let reversekeys;
			switch (type) {
				case "all":
					for (let i = 0; i < keys.length; i++) {
						Vue.delete(state.tags, keys[i]);
					}
					state.activeTag = "Home";
					break;
				case "else":
					for (let i = 0; i < keys.length; i++) {
						if (keys[i] !== state.activeTag) {
							Vue.delete(state.tags, keys[i]);
						}
					}
					break;
				case "left":
					for (let i = 0; i < keys.length; i++) {
						if (keys[i] === state.activeTag) {
							return;
						}
						Vue.delete(state.tags, keys[i]);
					}
					break;
				case "right":
					reversekeys = keys.reverse();
					for (let i = 0; i < keys.length; i++) {
						if (reversekeys[i] === state.activeTag) {
							return;
						}
						Vue.delete(state.tags, reversekeys[i]);
					}
					break;
			}
		},
	},
	actions: {
		/**
		* 关闭 tag
		* @param {*} tag: tag 的 key
		*/
		closeTagSelf({ state }, tag) {
			return new Promise((resolve) => {
				const keys = Object.keys(state.tags);
				if (tag === state.activeTag) {
					const i = keys.indexOf(tag);
					if (i < keys.length - 1) {
						state.activeTag = keys[i + 1];
					} else {
						state.activeTag = keys[i - 1];
					}
				}
				Vue.delete(state.tags, tag);
				resolve(state.activeTag)
			})
		},
	},
};
